import {request, responseWrapper} from "../request";
import * as _ from '../core';
import {hideLoading, hintError, hintSuccess, showLoading, showModal} from '../ui';

//合并默认处理
_.assign(request.defaults, {
	tipsMsg: true,//是否提示消息,为false时关闭所有提示信息
	tipsSuccessMsg: true,//是否提示消息
	tipsErrorMsg: true,//是否提示错误信息

	responseRaw: false,//是否返回原始数据

	//请求结束事件
	complete: function(options) {
		const config = options.config;
		if (config.showLoading !== false) {
			hideLoading();
		}
	}
});

// 添加请求前拦截器
request.addRequestInterceptor((config) => {
	if (config.showLoading !== false) {
		const showLoadingText = typeof config.showLoading === "string" ? config.showLoading : '请稍后...';
		showLoading(showLoadingText);
	}
	return $.Deferred().resolve(config);
});

//添加服务器返回结果拦截器
request.addResponseInterceptor((res) => {
	const {config, data} = res;
	const status = responseWrapper(data);

	if (status.isSuccess) {
		if (config.tipsMsg && config.tipsSuccessMsg) {
			hintSuccess(status.msg === 'ok' ? "操作成功！" : (status.msg || "操作成功！"));
		}
		return config.responseRaw ? res : data;
	} else {
		if (status.code === -1) { //未登录
			if (window.login) {
				return window.login().then(function() {
					return request(config);
				});
			} else if (status.url) {
				window.location.href = status.url;
			} else if (config.loginUrl) {
				window.location.href = config.loginUrl;
			} else {
				window.location.reload();
			}

			return $.Deferred().reject({
				errMsg: '登录已失效！'
			});
		} else if (status.code === -2) { //无权限
			if (config.tipsMsg && config.tipsErrorMsg) {
				showModal({
					icon: 'unauthorized',
					content: status.msg
				});
			}
			return $.Deferred().reject(res);
		} else if (status.code === -3) { //重复登录
			hintError(status.msg);
			setTimeout(function() {
				if (data.url) {
					window.location.href = data.url;
				}
			}, 1500);
			return $.Deferred().reject(res);
		} else {
			if (config.tipsMsg && config.tipsErrorMsg) {
				hintError(status.msg || "操作失败！");
			}
			return $.Deferred().reject(res);
		}
	}
}, (err) => {
	const config = err.config;
	if (config.tipsMsg && config.tipsErrorMsg) {
		hintError('服务繁忙，请稍后尝试！');
	}
	return $.Deferred().reject(err);
});
